package com.snowRemovingUser.service.impl;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.snowRemovingUser.domain.TAccessStatistics;
import com.snowRemovingUser.domain.TCustomer;
import com.snowRemovingUser.domain.TOrgan;
import com.snowRemovingUser.dto.LoginDto;
import com.snowRemovingUser.mapper.TAccessStatisticsMapper;
import com.snowRemovingUser.mapper.TCustomerMapper;
import com.snowRemovingUser.mapper.TOrganMapper;
import com.snowRemovingUser.service.ICustomerLoginService;
import com.snowRemovingUser.util.DateUtil;
import com.snowRemovingUser.util.Md5Utils;
import com.snowRemovingUser.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Service
public class CustomerLoginServiceImpl implements ICustomerLoginService {



    @Autowired
    private TCustomerMapper tCustomerMapper;

    @Autowired
    private TOrganMapper tOrganMapper;

    @Autowired
    private TAccessStatisticsMapper tAccessStatisticsMapper;



    /**
     *  登录验证
     * @param loginDto
     * @return
     */
    public AjaxResult login(LoginDto loginDto) {

        // 登录前置校验
        loginPreCheck(loginDto);

        //去数据库查询
        TCustomer tCustomer = tCustomerMapper.selectTCustomerByUserName(loginDto.getUsername());
        if (tCustomer==null) {

            AsyncManager.me().execute(AsyncFactory.CustomerLogininfor(loginDto.getUsername(), Constants.LOGIN_FAIL, "输入的账号不存在"));
            throw new RuntimeException("账号不存在");
        }

        //验证密码是否输入正确
        String inputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getPassword() + tCustomer.getSalt());
        if (!tCustomer.getPassword().equals(inputMd5Pwd)){

            AsyncManager.me().execute(AsyncFactory.CustomerLogininfor(loginDto.getUsername(), Constants.LOGIN_FAIL, "密码输入错误"));
            throw new RuntimeException("密码错误");
        }

        AsyncManager.me().execute(AsyncFactory.CustomerLogininfor(loginDto.getUsername(), Constants.LOGIN_SUCCESS, "登录成功"));

        final String ip = IpUtils.getIpAddr();
        tCustomer.setLoginIp(ip);
        tCustomer.setLoginDate(new Date());
        tCustomerMapper.updateTCustomer(tCustomer);

        //记录该账户登录次数
        Date today = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String eventTimeStr = simpleDateFormat.format(today);
        Date date = DateUtil.toDate(eventTimeStr, "yyyy-MM-dd");
        TAccessStatistics tAccessStatistics = tAccessStatisticsMapper.selectTAccessStatisticsByToDay(date);
        if (tAccessStatistics==null){

            TAccessStatistics AccessStatistics = new TAccessStatistics();
            AccessStatistics.setLoginTime(date);
            AccessStatistics.setCustomerNo(1);
            tAccessStatisticsMapper.insertTAccessStatistics(AccessStatistics);
        }else {

            tAccessStatistics.setCustomerNo(tAccessStatistics.getCustomerNo()+1);
            tAccessStatisticsMapper.updateTAccessStatistics(tAccessStatistics);
        }

        TOrgan tOrgan = tOrganMapper.selectTOrganById(tCustomer.getOrganId());

        if (tOrgan.getOrganName().equals("所有机构")){

            tOrgan.setOrganName("冕宁,荥经");
        }
        //封装数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("Login",tCustomer.getAccountNumber());
        map.put("UserName",tCustomer.getNickName());
        map.put("highwayManagementIds",tOrgan.getOrganCode());
        map.put("UnitNo",tOrgan.getUnitNo());
        map.put("accessKeyId","A67293B285393FBD");
        map.put("accessKeySecret","1C782D69E013EBFCAF0F2DDD613FDC");
        map.put("highwayManagementIdsName",tOrgan.getOrganName());
        //map.put("organId",tCustomer.getOrganId());
        //map.put("function_switch","notice,overview,work,patrol,video");
        //map.put("AllRights",",001002001,001001002,099001,");
        return  AjaxResult.success(map);
    }


    /**
     * 修改密码
     * @param loginDto
     * @return
     */
    @Override
    public AjaxResult loginUpdate(LoginDto loginDto) {

        //去数据库查询
        TCustomer tCustomer = tCustomerMapper.selectTCustomerByUserName(loginDto.getUsername());
        //验证旧密码是否输入正确
        String inputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getOldPwd() + tCustomer.getSalt());
        if (!tCustomer.getPassword().equals(inputMd5Pwd)){

            throw new RuntimeException("原密码错误");
        }

        //修改新密码
        String salt = StrUtils.getComplexRandomString(32);
        String SaltMd5 = Md5Utils.encrypByMd5(loginDto.getNewPwd() + salt);
        tCustomer.setSalt(salt);
        tCustomer.setPassword(SaltMd5);
        return AjaxResult.success(tCustomerMapper.updateTCustomer(tCustomer));
    }




























    /**
     *
     * @param loginDto
     */
    public void loginPreCheck(LoginDto loginDto)
    {

        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.CustomerLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }

    }
}
